package com.nstc.sftpExchange.service;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.nstc.sftpExchange.common.RestResponse;
import com.nstc.sftpExchange.entity.scope.UploadScope;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.convert.DataSizeUnit;
import org.springframework.stereotype.Service;
import org.springframework.util.unit.DataSize;
import org.springframework.util.unit.DataUnit;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;
import java.util.StringJoiner;

@Slf4j
@Service
public class SftpFileHandleService {

    @Resource
    private SftpService sftpService;

    public RestResponse<String> handleFile(String downloadName, String uploadName, UploadScope uploadScope) {
        log.info("请求参数：{}", uploadScope == null ? "无参数" : JSONObject.toJSONString(uploadScope));
        Long fileSize = uploadScope.getFileSize();
        if (fileSize == null || fileSize <= 0) {
            return RestResponse.failure("文件大小不能小于0");
        }

        StringJoiner stringJoiner = new StringJoiner(",");

        List<File> files = null;
        try {
            files = sftpService.doSftpDownload(downloadName, uploadScope.getDownloadSftpFile(), uploadScope.getNewName());
            for (File file : files) {
                long length = file.length() / 1024;
                if (length > uploadScope.getFileSize()){
                    stringJoiner.add(file.getName() + "超出文件大小");
                    break;
                }
                sftpService.doSftpUploadFile(uploadName, uploadScope.getUploadSftpDir(), file);
            }
        } catch (Exception e) {
            log.error("获取文件失败", e);
            return RestResponse.failure("获取文件失败", "");
        } finally {
            if (CollectionUtil.isNotEmpty(files)) {
                sftpService.deleteLocalFile(files);
            }
        }
        if (stringJoiner.length() > 0){
            return RestResponse.failure("获取文件成功，但部分文件超出大小", stringJoiner.toString());
        }else {
            return RestResponse.success("获取文件成功", stringJoiner.toString());
        }
    }
}

